function createPassword(chars, startIndex, maxLen) {
  const maxIndex = chars.length - 1;
  let curIndex = [...startIndex];

  return function getPassword () {
    let p = ""; // 生成的密码
    let jw = 1; // 进位

    for (let i = curIndex.length - 1; i >= 0; i--) {
      const index = curIndex[i];
      p = `${chars[index]}${p}`;

      // 进行下一个密码索引生成
      const nextIndex = index + jw;
      if (nextIndex > maxIndex) {
        jw = 1;
        curIndex[i] = 0;
      } else {
        jw = 0;
        curIndex[i] = nextIndex;
      }
    }

    // 如果已经超位了，增加一位
    if (jw) {
      curIndex.unshift(0);
    }

    // 如果密码长度已经超过最大长度
    if (p.length > maxLen) {
      return [false];
    }

    return [p, curIndex];
  };
}

module.exports = createPassword;
